package com.basic.technology.study.introduction.thread.queue;

import java.util.PriorityQueue;

public class ProduceAndConsumerNormal {

    private int queueSize = 10;

    private PriorityQueue<Integer> queue = new PriorityQueue(queueSize);

    public static void main(String[] args) throws InterruptedException {


        final ProduceAndConsumerNormal produceAndConsumerNormal = new ProduceAndConsumerNormal();
//        System.out.println(produceAndConsumerNormal.queue.size());
        Produce produce = produceAndConsumerNormal.new Produce();
        Consumer consumer = produceAndConsumerNormal.new Consumer();

        produce.start();
        consumer.start();


    }


    class Produce extends Thread {

        @Override
        public void run() {
            produce();
        }

        public void produce() {
            while (true) {
                synchronized (queue) {
                    while (queue.size() >= queueSize) {
                        try {
                            System.out.println("队列满，等待有空余空间");
                            queue.wait(5000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                            queue.notify();
                        }
                    }
                    queue.offer(1);        //每次插入一个元素
                    queue.notify();
                    System.out.println("向队列取中插入一个元素，队列剩余空间：" + (queueSize - queue.size()));
                }
            }
        }
    }

    class Consumer extends Thread {

        @Override
        public void run() {
            consumer();
        }

        public void consumer() {
            while (true) {
                synchronized (queue) {
                    while (queue.size() == 0) {
                        System.out.println("队列空，等待数据");
                        try {
                            queue.wait(5000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                            queue.notify();
                        }
                    }
                    queue.poll();//每次移走队首元素
                    queue.notify();
                    System.out.println("从队列取走一个元素，队列剩余" + queue.size() + "个元素");
                }
            }
        }
    }


}
